package com.cjx.learn.listener;

import com.cjx.learn.dto.MessageInfo;
import com.cjx.learn.service.WebsocketHandler;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.io.IOException;

/**
* webmq监听器
* @author cjunxian
* @date 2021/9/3
*/
@Component
@Slf4j
public class WeqMqListener {

    @RabbitListener(queues = "#{mqconfig.getQueueName()}")
    @RabbitHandler
    public void onMessage(MessageInfo msg, Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            //通知用户
            WebsocketHandler.sendMessage(msg.getUsername(),msg.getMessage());
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            channel.basicNack(deliveryTag, false, false);
            log.info("消息被否定确认！");
        }
    }

}
